#include "table.h"
#include <vector>
#include <sstream>

using namespace CppStory;

Table::Table()
: row_count(0)
, col_count(0)
{
}

void Table::set_str(std::string s)
{
    table_str = s;
}

std::vector<std::string> & Table::split(const std::string &s, char delim, std::vector<std::string> &elems)
{
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> Table::split(const std::string &s, char delim)
{
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

std::string Table::trim(std::string& str)
{
    str.erase(0, str.find_first_not_of(' '));       //prefixing spaces
    str.erase(str.find_last_not_of(' ')+1);         //surfixing spaces
    return str;
}

void Table::clear()
{
    std::map <std::string, std::vector <std::string> >::iterator iter;
    for (iter = data.begin(); iter != data.end(); ++iter)
        (*iter).second.clear();
    data.clear();
    heads.clear();

    row_count = 0;
    col_count = 0;
}

void Table::parse()
{
    clear();

    std::vector<std::string> temp_fields = split(table_str, '|');
    if (temp_fields.size() <= 1)
        return;

    std::vector<std::string> fields;
    std::vector<std::string>::iterator iter;
    for (iter = temp_fields.begin(), ++iter; iter != temp_fields.end(); ++iter)
        fields.push_back(trim(*iter));

    for (iter = fields.begin(); iter != fields.end(); ++iter)
    {
        if (*iter != "")
            heads.push_back(*iter);
        else
        {
            ++iter;
            break;
        }
    }

    col_count = heads.size();
    bool end_at_row = false;

    std::vector<std::string>::iterator head_iter = heads.begin();
    int col_index = 0;
    for (;iter != fields.end();)
    {
        data[*head_iter].push_back(*iter);
        ++head_iter;
        col_index++;
        if (col_index == col_count)
        {
            head_iter = heads.begin();
            col_index = 0;
            ++iter;
            if (iter != fields.end())
                ++iter;
            row_count++;
            end_at_row = true;
        }
        else
        {
            ++iter;
            end_at_row = false;
        }
    }
    if (!end_at_row)
        clear();
}

